//
//  RecruitViewController.m
//  SafeFoodManagerDemo
//
//  Created by ios-1 on 2018/3/5.
//  Copyright © 2018年 bob. All rights reserved.
//

#import "RecruitViewController.h"
#import "PatrolTableViewCell.h"
#import "PatrolListTableViewCell.h"
#import "RecruitModel.h"
#import "SendPatrolViewController.h"
#import "AddRecruitViewController.h"
#import "LookInforViewController.h"
@interface RecruitViewController ()
@property(nonatomic,copy)NSString*SearchKeyWord;
@property(nonatomic,copy)NSString*positionId;      //当前岗位ID
@property(nonatomic,copy)NSString*shopId;          //当前岗位商户ID
@property(nonatomic,assign)BOOL is_selectPosition; //是否点击当前岗位
@end

@implementation RecruitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"招聘管理";
    
    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"PatrolTableViewCell" bundle:nil] forCellReuseIdentifier:@"Dcell"];
    [self.homeTableView registerNib:[UINib nibWithNibName:@"PatrolListTableViewCell" bundle:nil] forCellReuseIdentifier:@"Ucell"];
    
    [self.homeTableView.mj_header beginRefreshing];
    // Do any additional setup after loading the view.
}

#pragma mark-tablevie代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecruitData *data=self.dataArr[indexPath.row];
    
    PatrolListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Ucell" forIndexPath:indexPath];
    
    cell.deleStatue=self.deleStatue;//是否编辑状态
    cell.isRecruit = YES;
    cell.recruitdata=data;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecruitData *data=self.dataArr[indexPath.row];
    if(self.isEdit)
    {
        if (self.isdeleMore) {
            
            if (self.deleStatue) {
                
                data.Seleclt=!data.Seleclt;
                
                [self ChangeStatues];
                
                [self.homeTableView reloadData];
            }
            
        }else{
            [self.homeTableView reloadData];
        }
        
        self.is_selectPosition = YES;
        self.positionId = data.ID;
        self.shopId = [NSString stringWithFormat:@"%zd",data.shopId];
        [self addNewgoods];
    }else{
        LookInforViewController *Infor=[LookInforViewController new];
        
        Infor.reqUrl=@"/index.php/FoodCheckApi/postAddInfo.json";
        
        Infor.params=@{@"id":[NSString stringWithFormat:@"%@",data.ID.length>0?data.ID:@""],@"shopId":[NSString stringWithFormat:@"%zd",data.shopId]};
        
        Infor.title=@"商品详情";
        
        [self.navigationController pushViewController:Infor animated:YES];
    }
    
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isdeleMore) {
        return YES;
    }
    return NO;
}

-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        RecruitData *data=self.dataArr[indexPath.row];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%@",data.ID]];
        
        [self DelPostion:arr];
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 20;
}

-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    
    view.tintColor=TBColorTableViewBg;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.1;
    
}

-(void)DelPostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/postDel.json" andrequestTime:5 andParams:@{@"ids":params} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:PatrolListType];
    
    
    if (isSelf) {
        
        if ([self.Reqmodel.ptype isEqualToString:@"1"]) {
            
            Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
            
        }else if ([self.Reqmodel.ptype isEqualToString:@"2"])
        {
            
            NSArray *PostArr= [USER_DEFAULT objectForKey:@"TBChoose"];//如果本地存在则读取本地的
            
            if (PostArr.count!=0) {
                
                Choose.CustomArr=PostArr;
                
            }else{
                
                Choose.CustomArr=@[@{@"fieldName":@"marketIds",@"name":@"开办方",@"value":@""},@{@"fieldName":@"type",@"name":@"",@"value":@""},@{@"fieldName":@"checkUserIds",@"name":@"检查员",@"value":@""},@{@"fieldName":@"startDate",@"name":@"开始日期",@"value":@""},@{@"fieldName":@"endDate",@"name":@"结束日期",@"value":@""}];
            }
        }
        
    }else{
        
        Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
    }
    Choose.SearchPlace=self.searchName;
    
    Choose.KeyWord=self.SearchKeyWord;
    
    Choose.Lshopid=self.Reqmodel.shopId;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.Reqmodel.params=paras;
        
        self.SearchKeyWord=keyword;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for (RecruitData *data in self.dataArr) {
            
            data.Seleclt=NO;
        }
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    
    for (RecruitData *data in self.dataArr) {
        
        data.Seleclt=YES;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    for (RecruitData *data in self.dataArr) {
        
        data.Seleclt=NO;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for (RecruitData *data in self.dataArr) {
        
        if (data.Seleclt) {
            
            [arr addObject:[NSString stringWithFormat:@"%@",data.ID]];
        }
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPostion:arr];
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (RecruitData *data in self.dataArr) {
        
        if (data.Seleclt) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    GetRegisterInforModel *model=[GetRegisterInforModel new];
    
    model.shopId=self.is_selectPosition?self.shopId:[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    
    model.token=[LoginStatuesModel getUserToken];
    
    model.id = self.positionId.length>0?self.positionId:@"";
    
    AddRecruitViewController *addPeople=[AddRecruitViewController new];
    
    addPeople.requrl=@"/index.php/FoodCheckApi/postAddInfo.json";
    
    addPeople.Reqmodel=model;
    
    addPeople.postUrl=@"/index.php/FoodCheckApi/postAdd.json";
    
    addPeople.title=self.is_selectPosition?@"编辑信息":@"新增招聘";
    
    addPeople.BtnStr=self.is_selectPosition?@"保存":@"新增";
    
    addPeople.OptionSussStr=self.is_selectPosition?@"保存成功":@"新增成功";
    
    addPeople.block=^()
    {
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    self.is_selectPosition = NO;
    [self.navigationController pushViewController:addPeople animated:YES];
}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}


-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/postList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        RecruitModel *InforModel=[RecruitModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",[responseObject[@"totalRecord"]integerValue],@"岗位"];
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
                [self.homeTableView reloadData];
                
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
